<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入角色姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="searchClick"
              size="medium">搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建角色"
                   type="primary"
                   icon="el-icon-plus"
                   size="medium"
                   perms="ROLE_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh">刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        class="elTable"
        ref="tableRef">
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column prop="roleName" label="角色名称" align="center"/>
        <el-table-column prop="roleDesc" label="角色描述" align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="createTime" width="170">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <perButton label="分配菜单权限"
                       type="primary"
                       size="mini"
                       :disabled="row.roleCode == 'RO001'"
                       perms="ROLE_BUTTON"
                       @click="handlerMenu(row)"></perButton>
            <perButton label="编辑"
                       type="warning"
                       size="mini"
                       :disabled="row.roleCode == 'RO001'"
                       perms="ROLE_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除"
                       type="danger"
                       size="mini"
                       :disabled="row.roleCode == 'RO001'"
                       perms="ROLE_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="pagination"
      />
    </el-card>

    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="roleModelRef"
            :model="newAccountModel"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="newAccountModel.roleName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input
                v-model="newAccountModel.roleDesc"
                :disabled="detailsDisabled"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 弹框 -->
    <yc-dialog ref="roleDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content">
          <el-table
            :data="menuData"
            border
            style="width: 100%"
            class="elTable"
            row-key="id"
            ref="menuRef"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" label="" width="100" align="center"/>
            <el-table-column prop="menuName" label="菜单名称" align="center"/>
            <el-table-column prop="menuDesc" label="菜单描述" align="center"/>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogMenuSave">确定</el-button>
        <el-button @click="$refs.roleDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryRolePage,
    queryOneRole,
    updateRole,
    insertRole,
    deleteRole,
    queryMyRoleMenuList,
    bindMenu
  } from "@/api/appUserControl/role"
  import { queryRoleList } from "@/api/appUserControl/menuControl"

  export default {
    data() {
      return {
        isGlobalMessageShow: false,
        isGlobalMessageBoxShow: false,
        messageTitleDes: "",
        message: "",
        messageBoxSaveShow: false,
        loading: false,
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 20,
        count2: 10,
        detailsDisabled: false, //详情 如果为true代表禁用状态
        selectOptions: [
          {
            label: "正常/停用状态（全部）",
            value: null
          },
          {
            label: "正常",
            value: 1
          },
          {
            label: "禁用",
            value: 0
          }
        ],
        searchModel: {
          userName: "",
          status: "" //正常/停用状态（全部）
        },

        newAccountModel: {
          roleName: "",
          roleDesc: "",
          id: ""
        },
        centerTitle: "",
        dialogTitle: "",
        editorId: "",
        rules: {
          roleName: [
            { required: true, message: "请输入角色名称", trigger: "blur" }
          ]
        },
        menuData: [],
        selectData: [],
        selectData2: [],
        roleCode: "",

        checkedData: [],
        addOrUpdateLoading: false,
        projectPermission: false
      }
    },
    components: {
      ycDialog,
      perButton
    },
    created() {
      this.getAccountData()
    },
    methods: {
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const { userName, status } = tableInfo
          const { object } = await queryRolePage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            roleName: userName
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const { object } = await queryRolePage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },

      /**
       * 新建账户
       * */
      async handlerAccount() {
        this.centerTitle = "添加"
        this.dialogTitle = "添加"

        this.editorId = ""

        if (this.$refs.roleModelRef) {
          this.$refs.roleModelRef.clearValidate()
          this.$refs.roleModelRef.resetFields()
        }
        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
      },

      /**
       * 修改按钮
       */
      async handlerEdit(row) {
        this.centerTitle = "编辑"
        this.dialogTitle = "编辑"
        this.editorId = row.id

        if (this.$refs.roleModelRef) {
          this.$refs.roleModelRef.clearValidate()
          this.$refs.roleModelRef.resetFields()
        }

        this.newAccountModel.roleName = row.roleName
        this.newAccountModel.id = row.id
        this.newAccountModel.roleDesc = row.roleDesc

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
      },
      dialogSave() {
        this.$refs.roleModelRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.editorId) {
              const { id, roleName, roleDesc } = this.newAccountModel
              const { message, status } = await updateRole({
                id,
                roleName,
                roleDesc
              })

              if (status == 200) {
                this.$message.success(message)
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const { id, roleName, roleDesc } = this.newAccountModel
              const { message, status } = await insertRole({
                roleName,
                roleDesc
              })

              if (status == 200) {
                this.$message.success(message)
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      /**
       * 删除按钮
       */
      async handlerDelete({ id }) {
        this.$confirm("确定删除此角色吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { message } = await deleteRole({ id, isDeleted: 1 })
          if (message == "更新成功") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },


      // 分配菜单权限
      async handlerMenu(row) {
        this.dialogTitle = "分配菜单权限"
        this.editorId = row.id

        await this.queryMyRoleMenuList()
        await this.queryRoleList()

        this.$refs.roleDialog.dialogVisible = true

        for (let i = 0; i < this.selectData2.length; i++) {
          let row = this.menuData.find(item => {
            return this.selectData2[i].id == item.id
          })
          this.$nextTick(() => {
            this.$refs.menuRef &&
            this.$refs.menuRef.toggleRowSelection(row, true)
          })
        }
      },
      async queryMyRoleMenuList() {
        const { object } = await queryMyRoleMenuList({
          id: this.editorId
        })
        this.selectData2 = object
      },
      handleSelectionChange(data) {
        this.selectData = data
      },
      async queryRoleList() {
        const { object } = await queryRoleList()
        this.menuData = object
      },

      async dialogMenuSave() {
        if (this.selectData.length == 0) {

        } else {
          let arr = []
          arr = this.selectData.map(item => {
            return item.id
          })
          const { message, status } = await bindMenu({
            id: this.editorId,
            ids: arr.toString()
          })
          if (status == 200) {
            this.$message.success(message)
            this.getAccountData()
            this.$refs.roleDialog.dialogVisible = false
          }
        }
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {}
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },

      async messageBoxSave(show) {
        this.messageBoxSaveShow = show
      }
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      /*margin: 10px 20px;*/
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .content {
    height: 600px;

    .drawer-title {
      font-weight: 400;
      font-size: 24px;
      color: #000000;
      text-align: center;
      padding: 36px 0;
    }

    .form {
      padding: 0 10px;
    }
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
